(function($) {
	var upPullElement = null;
	var start = 0,Limit = 20,pid = -1
	var perInfo, TomcatUrl,path;
	var sourceData = []
	var searchDom
	mui.plusReady(function() {
		searchDom = mui('#search')[0]
		setup()
		if (searchDom) {
			setupSearch()
		}
	});

	function setup() { //原来的mui.plusReady
		mui('#slider').slider().stopped = true;
		var deceleration = mui.os.ios ? 0.003 : 0.0009;
		mui('.mui-scroll-wrapper').scroll({
			bounce: false,
			indicators: true, //是否显示滚动条
			deceleration: deceleration
		});
		mui('#scrollUl').on('tap','li',itemTapped) 
		var self = plus.webview.currentWebview()
		path = self.category
		perInfo = app.getState()
		TomcatUrl = perInfo.TomcatUrl
		if (mui('.mui-title')[0]) {
			plus.navigator.setStatusBarBackground('#24af96');
			plus.navigator.setStatusBarStyle('light');
			if (!searchDom && !self.from) {
				mui.back = function() {
					plus.navigator.setStatusBarBackground('#fff')
					plus.navigator.setStatusBarStyle('dark');
					var _self = plus.webview.currentWebview();
					_self.close("auto");
				}
			}
		}
		if (self.navTitle) {
			mui('.mui-title')[0].innerText = self.navTitle
		}
		var pullrefresh = document.getElementById('pullrefresh');
		mui.each(document.querySelectorAll('.mui-slider-group .mui-scroll'), function(index, pullRefreshEl) {
			mui(pullRefreshEl).pullToRefresh({
				down: {
					callback: function() {
						pulldownRefresh(this, pullRefreshEl);
					}
				},
				up: {
					callback: function() {
						upPullElement = this;
						pullupRefresh(this);
					}
				}
			});
		});
		if (self.pid) {
			pid = self.pid
			getFileListByCategory(null)
		}else{
			FindFileTree()
		}
	}

	var isPullUp = true;
	/*
	 * 上拉加载更多
	 */
	function pullupRefresh(endRefresh) {
		isPullUp = true;
		getFileListByCategory(endRefresh);
	}

	/*
	 * 下拉刷新列表
	 */
	function pulldownRefresh(endRefresh) {
		start = 0;
		sourceData = []
		mui('#scrollUl').off('tap','li',itemTapped) 
		mui('#scrollUl')[0].innerHTML = '';
		mui('#scrollUl').on('tap','li',itemTapped) 
		mui('#pullrefresh').scroll().scrollTo(0, 0, 100);
		isPullUp = false;
		if (upPullElement) {
			upPullElement.refresh(true);
		}
		getFileListByCategory(endRefresh);
	}

	
	function getFileListByCategory(endRefresh) {
		if (searchDom && searchDom.value == '') {
			if (endRefresh != null) {
				if (isPullUp) {
					endRefresh.endPullUpToRefresh();
				} else {
					endRefresh.endPullDownToRefresh();
				}
			}
			return
		}
		//Input|^pid|7^nurseid|0
		var pdict = {
			'parr':'Input|'+(searchDom?searchDom.value:'')+'^pid|'+pid+'^nurseid|'+perInfo['loginID'],
			'start': start,
			'limit': Limit
		} 
		var paramDict = {
			'method': 'web.INMOrgComm:FindTableList',
			'params': JSON.stringify(pdict),
			'type': 'RecQuery'
		}
		//console.log(JSON.stringify(pdict))
		$.DHCWebService(paramDict, function(result) {
			// console.log(JSON.stringify(result))
			plus.nativeUI.closeWaiting();
			if (result.msgcode != '1') {
				mui.toast(result.msg)
				if (endRefresh != null) {
					if (isPullUp) {
						endRefresh.endPullUpToRefresh();
					} else {
						endRefresh.endPullDownToRefresh();
					}
				}
				return
			}
			// var arrary = [{"FileDate":"2023-04-07--","FileName":"护士执业证书","FileSize":"413.31KB","FileType":"png","FileUrl":"Fileupdate/images/OrgFileList/2/运单信息.jpg","rw":"2||6"},
			// 	{"FileDate":"2021-01-19--","FileName":"视频播放","FileSize":"11.58MB","FileType":"mp4","FileUrl":"Fileupdate/images/drillFile/12/17、导航设置.mp4","rw":"2||1"},
			// 	{"FileDate":"2022-06-15--","FileName":"图片预览","FileSize":"1.07MB","FileType":"jpg","FileUrl":"Fileupdate/images/OrgFileList/2/运单信息.jpg","rw":"2||4"},
			// 	{"FileDate":"2022-06-15--","FileName":"txt","FileSize":"1.07MB","FileType":"txt","FileUrl":"Fileupdate/images/OrgFileList/2/test.txt","rw":"2||4"},
			// 	{"FileDate":"2024-04-26--","FileName":"文件1","FileSize":"565.69KB","FileType":"pdf","FileUrl":"Fileupdate/images/OrgFileList/2/文件1.pdf","rw":"2||11"}]
			var arrary = result.data
			if (arrary.length == 0) {
				if (start == 0) {
					var str = searchDom?'没有搜索到文件':'当前分类下没有文件'
					mui.toast(str);
				}
			}else{
				sourceData = sourceData.concat(arrary)
				updateUIs(arrary);
			}
			if (endRefresh != null) {
				if (isPullUp) {
					endRefresh.endPullUpToRefresh(arrary.length < Limit);
				} else {
					endRefresh.endPullDownToRefresh();
				}
			}
			start += arrary.length
		}, function(error) {
			mui.toast(error);
			plus.nativeUI.closeWaiting();
			if (endRefresh != null) {
				if (isPullUp) {
					endRefresh.endPullUpToRefresh();
				} else {
					endRefresh.endPullDownToRefresh();
				}
			}
		});
	}

	/*
	 * 更新文件列表
	 */
	function updateUIs(dataArr) {
		var scroll1Ul = document.getElementById("scrollUl");
		
		for (var i = 0; i < dataArr.length; i++) {
			var dict = dataArr[i]
			var tableviewcell = document.createElement('li');
			scroll1Ul.appendChild(tableviewcell)
			var fileType = dict['FileType'].toLowerCase()
			var imgUrl = '';
			var type2 = ''
			if (fileType == 'ppt' || fileType == 'pptx') { //ppt
				imgUrl = '../../dependence/home/images/ppt.png';
				type2 = 'ppt'
			} else if (fileType == 'pdf') { //pdf
				imgUrl = '../../dependence/home/images/pdf.png';
				type2 = 'pdf'
			} else if (fileType == 'doc' || fileType == 'docx') { //doc
				imgUrl = '../../dependence/home/images/doc.png';
				type2 = 'word'
			} else if (fileType == 'xls' || fileType == 'xlsx') { //表格
				imgUrl = '../../dependence/home/images/exl.png';
				type2 = 'xls'
			} else if (fileType == 'png' || fileType == 'jpeg'|| fileType == 'gif' || fileType == 'jpg' || fileType =='.bmp') {
				imgUrl = '../../dependence/home/images/img.png';
				type2 = 'img'
			} else if (fileType == 'mp4') { //表格
				imgUrl = '../../dependence/home/images/videoicon.png';
				type2 = 'video'
			} else if (fileType == 'txt'||fileType == 'json') { //表格
				imgUrl = '../../dependence/home/images/xxx.png';
				type2 = 'txt'
			} else {
				imgUrl = '../../dependence/home/images/xxx.png';
				type2 = 'file'
			}
			tableviewcell.id = start + i
			tableviewcell.setAttribute('class', 'mui-table-view-cell public-flex-row');
			tableviewcell.setAttribute('data-type', type2);
			tableviewcell.setAttribute('data-url', dict['FileUrl']);
			var html = '<div class="pdfIcon"><img src="'+imgUrl+'" /></div>' +
				'<div class="mui-media-body"><div class="filenameStyle">' + dict.FileName + '</div>' +
				'<div class="rightOneLine">' +
				'<div class="totalSize">' + dict.FileSize + '</div>' +
				'<div class="uploadTime">' + dict.CreateDate + '</div>' +
				'</div></div>'
			//console.log(html);
			tableviewcell.innerHTML = html
		}
	}
	function itemTapped() {
		localStorage['trainSubID'] = ''
		plus.nativeUI.showWaiting('正在监测文件是否存在')
		var url = TomcatUrl + '/' + this.getAttribute('data-url')
		var label = this.querySelector('.filenameStyle').innerText
		var fileType = this.getAttribute('data-type')
		if (fileType == 'video') {
			plus.nativeUI.closeWaiting()
			playVideo(label,url)
			return
		}
		mui.checkUrlReal(url, function() {
			plus.nativeUI.closeWaiting()
			if (fileType == 'img') {
				previewImages(url)
				return;
			}
			var pageName = ''
			switch (fileType) {
				case "pdf":
				case "word":
				case "ppt":
					pageName = '../../FilePreview/pdfReader.html'
					break;
				case "txt":
					pageName = '../../WKPlatformPages/filePreview.html'
					break;
				default:
					break;
			}
			if (pageName == '') {
				mui.toast('暂不支持此类型文件')
				return
			}
			plus.navigator.setStatusBarBackground('#fff');
			plus.navigator.setStatusBarStyle('dark');
			var webview = plus.webview.create(pageName, pageName, {
				background: '#fff',
				statusbar: {
					background: '#fff'
				}
			}, {
				'title': label,
				'fileUrl': url
			});
			webview.show('fade-in');
			webview.addEventListener('close', function() {
				plus.navigator.setFullscreen(false);
				plus.navigator.setStatusBarBackground('#24AF96');
				plus.navigator.setStatusBarStyle('light');
				plus.screen.lockOrientation("portrait-primary");
			});
		}, function() {
			plus.nativeUI.closeWaiting()
			mui.toast('文件不存在')
		})
	}

	function FindFileTree() {
		var pdict = {
			'par': 0,
			'dateFlag': '0',
			role: perInfo.maxRoleLevel,
			'appFlag': '1',
			'nurseid': perInfo['loginID'],
			'input': ''
		}
		var paramDict = {
			'method': 'web.INMOrgComm:FindFileTree',
			'params': JSON.stringify(pdict),
			'type': 'MethodNoFilter'
		}
		// console.log(JSON.stringify(pdict))
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result.msgcode == '1') {
				getPid(result.data)
				getFileListByCategory(null)
			} else {
				mui.toast(result.msg)
			}
		}, function(errorStr) {
			mui.toast(errorStr)
		});
	}

	function getPid(arr) {
		var pathArr = path.split('/')
		var currArr = arr
		for (var i = 0; i < pathArr.length; i++) {
			var text = pathArr[i]
			for (var j = 0; j < currArr.length; j++) {
				var dict = currArr[j]
				if (dict.label == text) { //看看需要找下级不
					if (i == pathArr.length - 1) { //最后一层
						pid = dict.id
					} else {
						currArr = dict.children
						if (currArr == undefined) {
							return
						}
					}
					break
				}
			}
		}
	}
	/*
	 * 播放视频
	 */
	function playVideo(titleStr, fileurl){
		var videoPlay = mui.openWindow({
			url:'../videoPlay.html',
			id:'../videoPlay',
			extras:{
				'fileurl':fileurl,
				'titleStr':titleStr
			}
		});
		videoPlay.addEventListener('close', function() {
			plus.navigator.setFullscreen(false);
			plus.navigator.setStatusBarBackground('#24AF96');
			plus.screen.lockOrientation("portrait-primary");
		});
	}
	
	/*
	 * 预览图片
	 */
	function previewImages(url){
		var imgData = []
		var index = 0
		mui('li').each(function (celli,cell) {
			var type = cell.getAttribute('data-type')
			if (type == 'img') {
				var currUrl = TomcatUrl +'/' + cell.getAttribute('data-url')
				if (currUrl == url) {
					index = imgData.length
				}
				imgData.push({'Internet':currUrl})
			}
		})
		var imgPlay = mui.openWindow({
			url:'../imgPlay.html',
			id:'../imgPlay',
			extras:{
				index:index,
				sourceData:imgData
			}
		});
		imgPlay.addEventListener('close', function() {
			plus.navigator.setStatusBarBackground('#24AF96');
		})
	}
	
	function setupSearch(){
		//语音识别完成事件
		searchDom.addEventListener('recognized', function(e) {
			pulldownRefresh(null)
		});
		var nativeWebview, imm, InputMethodManager;
		var initNativeObjects = function() {
			if (mui.os.android) {
				var main = plus.android.runtimeMainActivity();
				var Context = plus.android.importClass("android.content.Context");
				InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
				imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
			} else {
				nativeWebview = plus.webview.currentWebview().nativeInstanceObject();
			}
		};
		var showSoftInput = function() {
			if (mui.os.android) {
				var webview = plus.android.currentWebview();
				plus.android.importClass(webview);
				webview.requestFocus();
				imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
			} else {
				nativeWebview.plusCallMethod({
					"setKeyboardDisplayRequiresUserAction": false
				});
			}
			setTimeout(function() {
				searchDom.focus();
				searchDom.parentNode.classList.add('mui-active'); //第一个是search，加上激活样式
			}, 200);
		};
		initNativeObjects();
		showSoftInput();
		mui('body').on('input','#search',function(){
			pulldownRefresh(null)
		})
	}
})(mui)